#pragma once

#include<iostream>
#include<unordered_map>
#include<functional>

using task_t = std::function<void()>;

void DownLoad()
{
    std::cout << "我是下载任务..." << getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务..." << getpid() << std::endl;
}

void Sql()
{
    std::cout << "我是数据库同步任务..." << getpid() << std::endl;
}

static int number = 0;
class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }
    void InsertTask(task_t t)
    {
        tasks[number ++] = t;
    }
    int SelectTask() // 随机选择一个任务编号
    {
        return rand() % number;
        // 这里只是随机选择一个任务编号，
        // 与将这个任务编号派发给哪一个子进程无关
    }
    
    void Excute(int number)
    {
        if(tasks.find(number) == tasks.end()) return;
        tasks[number]();
    }
    ~TaskManger() {}
private:
    std::unordered_map<int, task_t> tasks;
};

TaskManger tm;

void Worker()
{
    while(true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if(n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if(n == 0) 
        {
            std::cout << "PID: " << getpid() << " quit" << std::endl;
            break;
        }
        else {}
    }
}